package com.skwyb.form.controller;

import com.alibaba.fastjson.util.IOUtils;
import com.skwyb.form.service.admin.AdminService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

@Log4j2
@RestController
@RequestMapping("/form")
public class LoginController {
    @Value("${file.storageDir}")
    private String storageDir;

    @Autowired
    private AdminService adminService;

    @PostMapping("/login")
    public String login(String account) {
        System.err.println(adminService.selectByAccount(account));
        return "234";
    }

    @GetMapping("/showFile")
    public void showFile(HttpServletRequest request, HttpServletResponse response, String path) {
        String imagePath = storageDir + path;
        response.reset();
        OutputStream output = null;// 得到输出流
        FileInputStream is = null;
        try {
            output = response.getOutputStream();
            String extension = path.substring(path.lastIndexOf(","));

            File file = new File(imagePath);
            if (file.exists()) {
                is = new FileInputStream(file);
                // 得到文件大小
                int i = is.available();
                byte[] fileBytes = new byte[i];
                // 读数据
                is.read(fileBytes);
                is.close();
                // 设置返回的文件类型
                response.setContentType("image/*");
                //这一步很重要，如果不设置预览正常，但是FileReader.src操作后就有问题。
                response.setContentType("image/".concat(extension).concat(";charset=UTF-8"));
                response.setHeader("Content-Disposition", "inline; filename=\"" + path.lastIndexOf("/") + "\"");
                output = response.getOutputStream();
                output.write(fileBytes);
                output.flush();
                output.close();
            }
        } catch (IOException e) {
            log.error(e);
        } finally {
            IOUtils.close(output);
            IOUtils.close(is);
        }
    }
}
